package lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zfj
 * @date 2021/10/17 -13:26
 * 测试lock锁
 */
public class TestLock {
	public static void main(String[] args) {
		TestLock2 lock2 = new TestLock2();
		new Thread(lock2).start();
		new Thread(lock2).start();
		new Thread(lock2).start();
	}
}
class TestLock2 implements Runnable{

	/**
	 * When an object implementing interface <code>Runnable</code> is used
	 * to create a thread, starting the thread causes the object's
	 * <code>run</code> method to be called in that separately executing
	 * thread.
	 * <p>
	 * The general contract of the method <code>run</code> is that it may
	 * take any action whatsoever.
	 *
	 * @see Thread#run()
	 */
	int tickNums=10;

	//定义lock锁
	private final ReentrantLock lock=new ReentrantLock();
	@Override
	public void run() {
		while (true){
			try {
				lock.lock();
				if(tickNums>0){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(tickNums--);
				}else {
					break;
				}
			}finally {
				lock.unlock();
			}
		}
	}
}
